import { useMemo } from 'react';
import { usePlatformStore } from '../../stores/platform';
import { PLATFORM_MENU_CONFIG, USER_MENU_CONFIG, filterMenuByPermissions, type PlatformMenuItem } from '../../constants/platformMenu';

/**
 * 平台菜单管理Hook
 * 基于本地配置和用户权限进行动态菜单渲染
 */
export const usePlatformMenus = () => {
  const { user, menuCodes } = usePlatformStore();

  // 计算用户角色
  const userRoles = useMemo(() => {
    return user?.roleCodes || [];
  }, [user?.roleCodes]);

  // 计算用户权限
  const userPermissions = useMemo(() => {
    return user?.permissions || [];
  }, [user?.permissions]);

  // 判断是否为超级管理员
  const isSuperAdmin = useMemo(() => {
    return userRoles.includes('super_admin');
  }, [userRoles]);

  // 将menuCodes转换为菜单配置映射
  const menuCodeToConfigMap = useMemo(() => {
    const allMenus = [...PLATFORM_MENU_CONFIG, ...USER_MENU_CONFIG];
    const map = new Map<string, PlatformMenuItem>();
    allMenus.forEach(menu => {
      map.set(menu.key, menu);
    });
    return map;
  }, []);

  // 根据menuCodes获取用户可访问的菜单配置
  const accessibleMenus = useMemo(() => {
    if (!user) {
      return [];
    }

    // 确保 dashboard 菜单始终显示给已登录用户
    const dashboardMenu = PLATFORM_MENU_CONFIG.find(menu => menu.key === 'dashboard');
    const baseMenus = dashboardMenu ? [dashboardMenu] : [];

    // 如果是超级管理员，返回所有菜单
    if (user.isSuperAdmin) {
      return PLATFORM_MENU_CONFIG;
    }

    // 根据用户的菜单权限过滤菜单
    const userMenus = PLATFORM_MENU_CONFIG.filter(menu => {
      // dashboard 菜单已经在 baseMenus 中，跳过重复添加
      if (menu.key === 'dashboard') {
        return false;
      }
      
      return menuCodes.includes(menu.key);
    });

    // 合并基础菜单和用户菜单
    return [...baseMenus, ...userMenus];
  }, [menuCodes, user]);

  // 用户下拉菜单
  const userDropdownMenus = useMemo(() => {
    return filterMenuByPermissions(
      USER_MENU_CONFIG,
      userPermissions,
      userRoles,
      isSuperAdmin
    );
  }, [userPermissions, userRoles, isSuperAdmin]);

  /**
   * 检查用户是否有访问指定菜单的权限
   */
  const hasMenuPermission = (menuCode: string): boolean => {
    if (isSuperAdmin) return true;
    return menuCodes.includes(menuCode);
  };

  /**
   * 检查用户是否有访问指定路径的权限
   */
  const hasPathPermission = (path: string): boolean => {
    if (isSuperAdmin) return true;
    
    const menu = [...PLATFORM_MENU_CONFIG, ...USER_MENU_CONFIG].find(m => m.path === path);
    if (!menu) return false;
    
    return menuCodes.includes(menu.key);
  };

  /**
   * 获取菜单的权重（order值）
   */
  const getMenuWeight = (menuCode: string): number => {
    const menu = menuCodeToConfigMap.get(menuCode);
    return menu?.order || 999;
  };

  return {
    // 数据
    accessibleMenus,
    userDropdownMenus,
    userMenuCodes: menuCodes,
    
    // 状态
    isSuperAdmin,
    userRoles,
    userPermissions,
    
    // 方法
    hasMenuPermission,
    hasPathPermission,
    getMenuWeight,
  };
};

export default usePlatformMenus;